<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import {
  getTaskNeedListApi,
  deleteTaskNeedApi,
  queryTaskApi,
  addTaskNeedApi,
  putTaskNeedApi
} from '@/api/dispatch/taskpool'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { TaskNeedType } from '@/api/dispatch/taskpool/types'
import { ElButton } from 'element-plus'

const ids = ref<string[] | number[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTaskNeedListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data,
      total: res.count
    }
  },

  fetchDelApi: async () => {
    const res = await deleteTaskNeedApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { task, ...param } = params
  searchParams.value = { ...param, task: JSON.stringify(task) }
  getList()
}

const { t } = useI18n()

const queryLoading = ref(false)
const ticketOptions = ref([])
const ticketRemoteMethod = async (query: string) => {
  if (query) {
    queryLoading.value = true
    try {
      const res = await queryTaskApi({ ticket_id: query })
      if (res) {
        ticketOptions.value = res.data
      }
    } finally {
      queryLoading.value = false
    }
  } else {
    ticketOptions.value = []
  }
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    fixed: true,
    type: 'selection',
    width: 80,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'index',
    label: t('common.index'),
    type: 'index',
    width: 80,
    fixed: true,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'ticket_id',
    label: '工单号',
    fixed: true,
    form: {
      component: 'Select',
      componentProps: {
        filterable: true,
        remote: true,
        remoteMethod: ticketRemoteMethod,
        remoteShowSuffix: true,
        loading: queryLoading,
        options: ticketOptions
      }
    }
  },
  {
    field: 'task.ao_id',
    label: 'AO号',
    fixed: true,
    form: {
      hidden: true
    }
  },
  {
    field: 'task.product_type',
    label: '型号',
    fixed: true,
    form: {
      hidden: true
    }
  },
  {
    field: 'task.flight',
    label: '架次',
    fixed: true,
    search: {
      componentProps: {
        placeholder: '多架次用英文逗号分隔'
      }
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'task.station',
    label: '工位',
    fixed: true,
    form: {
      hidden: true
    }
  },
  {
    field: 'task.position',
    label: '站位',
    fixed: true,
    form: {
      hidden: true
    }
  },
  {
    field: 'task.plan_start',
    label: '计划开始日期',
    table: {
      hidden: true
    },
    form: {
      hidden: true
    },
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  },
  {
    field: 'name',
    label: '辅料名',
    fixed: true
  },
  {
    field: 'type',
    label: '辅料类型',
    fixed: true,
    search: {
      hidden: true
    }
  },
  {
    field: 'number',
    label: '数量',
    fixed: true,
    search: {
      hidden: true
    }
  },
  {
    field: 'unit',
    label: '单位',
    fixed: true,
    search: {
      hidden: true
    }
  },
  {
    field: 'remark',
    label: '备注',
    fixed: true,
    search: {
      hidden: true
    }
  },
  {
    field: 'create_datetime',
    label: '创建时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('common.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 120,
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElButton onClick={() => action(data.row, 'edit')}>编辑</ElButton>
              {/* <ElButton type="danger" onClick={() => delData(data.row)}>
                {t('common.del')}
              </ElButton> */}
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TaskNeedType | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('common.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)

const delData = async (row: TaskNeedType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: TaskNeedType) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: TaskNeedType, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.edit' : 'common.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res =
        actionType.value === 'add' ? await addTaskNeedApi(formData) : await putTaskNeedApi(formData)
      if (res) getList()
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('common.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('common.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      :fit="true"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="900px" max-height="380px">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :form-schema="allSchemas.formSchema"
    />

    <Detail
      v-if="actionType === 'detail'"
      :current-row="currentRow"
      :detail-schema="allSchemas.detailSchema"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
</template>
